﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.Library.CommonClass
{
    public class IELogicHelper
    {
        static DataTable dt = null;

        static  List<ConfigModel> lst = null;
        
        public static  string GetLogicValue(string DWG_NO,string PART_NO, string FuncLogic)
        {
            string errorMessage = DWG_NO + ";" + PART_NO + ";" + FuncLogic;
            try
            {
                if (string.IsNullOrEmpty(FuncLogic)|| FuncLogic=="0")
                {
                    Lamex.Common.IniFile ini = new Common.IniFile(Application.StartupPath + "\\RecordLostWorkTime.ini");
                    string str = ini.IniReadValue("Configuration", "RecoredName");
                    str += @"\r\n" + errorMessage;
                    ini.IniWriteValue("Configuration", "RecoredName", str);
                    //L1
                    return "0";
                }

                dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(" select * from IE_Part_SizeParmList where DWG_NO = '" + DWG_NO + "' and  PART_NO='" + PART_NO + "'");
               
                //DWG_NO = '" + DWG_NO + "' and
                if (dt.Rows.Count == 0)
                {
                    Lamex.Common.IniFile ini = new Common.IniFile(Application.StartupPath + "\\RecordLostWorkTime.ini");
                    string str = ini.IniReadValue("Configuration", "RecoredName");
                    str += @"\r\n"+errorMessage;
                    ini.IniWriteValue("Configuration", "RecoredName", str);
                    //L2
                    return "900000";//尺寸表有无数据返回错误代码
                }
                lst = ConvertInterface.SetVarValue(dt);
                string Msg = FuncLogic;
                string error = ConvertInterface.CheckExpressConvertValue(Msg, lst,true);
                if(!string.IsNullOrEmpty(error))
                {
                    return error;
                }
                if (!FuncLogic.Contains("?"))
                {
                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = ConvertInterface.ExpressConvertValue(FuncLogic, lst, true);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                        return backValue;
                }
                string firstIndex = FuncLogic.Substring(0, 1);
                if (firstIndex != "?") return "L1";

                int iCount = FuncLogic.Split(new char[] { ':' }).Length - 1;
                int idx = ConvertInterface.RecFindFirstIndex(FuncLogic, ":");

                if (iCount == 0)
                {
                    if (FuncLogic.ToLower().Contains("1/rounddown"))
                    {
                        string[] arr = FuncLogic.Split('(');
                        if (arr[0].ToString().ToLower().Trim() != "?1/rounddown") return "Error 1";
                        int idxLeft = ConvertInterface.RecFindFirstIndex(FuncLogic, "(");

                        string strLeft = FuncLogic.Substring(idxLeft, FuncLogic.Length - idxLeft);
                        int idxRight = ConvertInterface.RecFindFirstIndex(strLeft, ")");
                        string strRight = strLeft.Substring(0, idxRight);

                        //double iMin = Convert.ToDouble(ConvertInterface.ExpressConvertValue(strRight, lst, true));
                        //if (iMin < 1) iMin = 1;
                        //(1 / Math.Floor(iMin)).ToString();
                        string backValue = "";//返回数据大于90009时为90000；否则为原值；
                        string dvalue = RecValue(strRight);
                        if (double.Parse(dvalue) > 90009)
                            backValue = "900000";
                        else
                            backValue = dvalue;
                        return backValue;

                        //return RecValue(strRight);
                    }
                    else
                    {
                        string funcLogic = FuncLogic;
                        funcLogic = funcLogic.Replace('?', ' ');

                        string backValue = "";//返回数据大于90009时为90000；否则为原值；
                        string dvalue = ConvertInterface.ExpressConvertValue(funcLogic, lst, true);
                        if (double.Parse(dvalue) > 90009)
                            backValue = "900000";
                        else
                            backValue = dvalue;
                        return backValue;

                        //return ConvertInterface.ExpressConvertValue(funcLogic, lst, true);
                    }
                }
                else if (iCount == 1)
                {
                    if (!CheckRuleStr(FuncLogic)) return "L1";
                    string subLogic = FuncLogic.Replace('?', ' ').Trim();
                    string[] strArray = subLogic.Split(':');
                    if (strArray.Count() < 2) return "L1";
                    //ConfigModel model = lst.Where(p => p.Name == strArray[0].ToString()).FirstOrDefault();
                    //if (string.IsNullOrEmpty(model.Num.ToString())) return "L2";
                    double midVar = double.Parse(ConvertInterface.ExpressConvertValue(strArray[0].ToString(), lst, true));
                    if (ConvertInterface.IsCheckVarStr(strArray[1]))
                    {
                        string backValue = "";//返回数据大于90009时为90000；否则为原值；
                        string dvalue = ConvertInterface.GetNorStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
                        if (double.Parse(dvalue) > 90009)
                            backValue = "900000";
                        else
                            backValue = dvalue;
                        return backValue;

                        //return ConvertInterface.GetNorStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);


                    }
                    else
                    {
                        string backValue = "";//返回数据大于90009时为90000；否则为原值；
                        string dvalue = ConvertInterface.GetStrValue(midVar, strArray[1], lst);
                        if (double.Parse(dvalue) > 90009)
                            backValue = "900000";
                        else
                            backValue = dvalue;
                        return backValue;

                        //return ConvertInterface.GetStrValue(midVar, strArray[1], lst);
                    }
                }
                else
                {
                    if (!CheckRuleStr(FuncLogic)) return "L1";
                    string subLogic = FuncLogic.Replace('?', ' ').Trim();
                    string[] strArray = subLogic.Split(':');
                    if (strArray.Count() < 1) return "L1";
                    //ConfigModel model = lst.Where(p => p.Name == strArray[0].ToString()).FirstOrDefault();
                    //if (string.IsNullOrEmpty(model.Num.ToString())) return "L2";

                    double midVar = double.Parse(ConvertInterface.ExpressConvertValue(strArray[0].ToString(), lst, true));

                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = ConvertInterface.GetMoreStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                    return backValue;


                    //return ConvertInterface.GetMoreStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
                }

                return "L1";
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+":"+ errorMessage);
                return "";
            }
        }
       
        public static bool  CheckRuleStr(string FunLogic)
        {
            int m = 0;
            string strCheck = @"@?:,.+*-/|()WDW1D1W2D2THL12345678910";
            
            foreach(char c in FunLogic)
            {
                if (!strCheck.Contains(c))
                    m++;
            }
            if (m != 0) return false;
            return true;
        }
        
        private static string ComputerNormalValue()
        {
            return "";
        }
        /// <summary>
        /// 转换计算方法
        /// </summary>
        /// <param name="Logic"></param>
        /// <returns></returns>
        private static string ComputerVarValue(string Logic)
        {

            return "";
        }
        private static string RecValue(string Logic)
        {
            double iMin = Convert.ToDouble(ConvertInterface.ExpressConvertValue(Logic, lst, true));
            if (iMin < 1) iMin = 1;
            return (1 / Math.Floor(iMin)).ToString();
        }
        
    }
}
